﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace ClassLibraryMessageDataType
{
 public sealed   class StructByteConver
    {

        /// <summary>
        /// 结构体转数组
        /// </summary>
        /// <param name="structObj"></param>
        /// <returns></returns>
        public static byte[] StructToBytes(object structObj)
        {
            try
            {
                int size = Marshal.SizeOf(structObj);

                byte[] bytes = new byte[size];

                IntPtr structPtr = Marshal.AllocHGlobal(size);

                Marshal.StructureToPtr(structObj, structPtr, false);

                Marshal.Copy(structPtr, bytes, 0, size);

                Marshal.FreeHGlobal(structPtr);

                return bytes;
            }catch(Exception e)
            {
                Console.WriteLine("StructToBytes retnrn null\r\n"+e.Message);
                return null;
            }
        }
        /// <summary>
        /// 数组转结构体
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object BytesToStuct(byte[] bytes, Type type)
        {
            try
            {
                int size = Marshal.SizeOf(type);
            if (size > bytes.Length)
            {
                return null;
            }
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.Copy(bytes, 0, structPtr, size);
            object obj = Marshal.PtrToStructure(structPtr, type);
            Marshal.FreeHGlobal(structPtr);
            return obj;
            }
            catch (Exception e)
            {
                Console.WriteLine("StructToBytes retnrn null\r\n" + e.Message);
                return null;
            }
        }
    }
}
